﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;

namespace TireService.Web.Casehandling
{
    public partial class BusinessCustomerList : System.Web.UI.Page
    {

        protected void Page_Init(object sender, EventArgs e)
        {
            // Register export button as full postback - otherwise it wount work because it is inside a update panel
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(this.btnExport.FindControl("btnExport"));
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {

            }

            // Bind customer data to gridview
            BindCustomerData(db);

            // Change gridview pagesize based on dropdownlist
            gvCustomer.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind customer data to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void BindCustomerData(TireServiceDB db)
        {
            gvCustomer.DataSource = db.GetBusinessCustomers();
            gvCustomer.DataBind();
        }

        #region Private Functions

        /// <summary>
        /// Function that runs specific action
        /// </summary>
        /// <param name="Action">Id for action to run</param>
        protected void SubmitAction(int Action)
        {
            if (Action == 0)
            {
                throw new ArgumentException("Ingen handling valgt.");
            }
            if (Action == 1)
            {
                
            }
        }

        /// <summary>
        /// Function that change grouping in order gridview
        /// </summary>
        /// <param name="ViewIndex">Integer setting the grouping mode</param>
        protected void GroupOrderData(int ViewIndex)
        {
            gvCustomer.ClearSort();
            gvCustomer.GroupSummary.Clear();
            switch (ViewIndex)
            {
                case 0:
                    // Nothing - clear grouping

                    break;
                case 1:
                    gvCustomer.GroupBy(gvCustomer.Columns["City"]);

                    break;
                //case 2:
                //    gvOrder.GroupBy(gvOrder.Columns["CustomerNumber"]);

                //    break;
                //case 3:
                //    gvOrder.GroupBy(gvOrder.Columns["PhotoDate"]);
                //    gvOrder.GroupBy(gvOrder.Columns["CustomerNumber"]);

                //break;
            }
            gvCustomer.ExpandAll();
        }

        #endregion

        #region Control Functions

        /// <summary>
        /// Button function for creating a new customerList
        /// </summary>
        protected void btnNewCustomer_Click(object sender, EventArgs e)
        {
            // Go to edit mode
            Session["CustomerId"] = null;
            Response.Redirect("~/Casehandling/EditCustomer.aspx");
        }

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.SelectedValue == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.SelectedValue == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.SelectedValue == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.SelectedValue == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        /// <summary>
        /// Button function that submit selected action in action dropdownlist
        /// </summary>
        protected void btnSubmitAction_Click(object sender, EventArgs e)
        {
            try
            {
                SubmitAction(Convert.ToInt32(ddlAction.SelectedValue));
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        /// <summary>
        /// Dropdown list function that change gridview grouping when selected item is changed
        /// </summary>
        protected void ddlView_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Group data
            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        #endregion

        #region GridView Functions

        /// <summary>
        /// Gridview function that handles edit selection of customers
        /// </summary>
        protected void gvCustomer_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            if (e.ButtonID == "Edit")
            {
                try
                {
                    // Get contactid
                    object cellCustomerId = gvCustomer.GetRowValues(e.VisibleIndex, "CustomerId");

                    // Go to edit mode
                    Session["CustomerId"] = Convert.ToInt32(cellCustomerId);
                    Response.Redirect("~/Casehandling/EditCustomer.aspx");
                }
                catch (Exception ex)
                {
                    if ((ex) is ArgumentException)
                    {
                        // User error - arguments not valid - show error message
                        lMessage.Text = ((ArgumentException)ex).Message;
                    }
                    else
                    {
                        // System error - show general error message
                        lMessage.Text = "Fejl opstod - venligst prøv igen";
                    }
                }
                finally
                {
                    // Update message panel
                    upMessage.Update();
                }
            }
        }

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvCustomer_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn Type: Show country name
            if (e.Column.FieldName == "CountryName")
            {
                // Get countryid
                int countryid = Convert.ToInt32(e.GetListSourceFieldValue("CountryId"));

                TireServiceDB db = new TireServiceDB();

                // Change field value
                e.Value = db.GetCountryName(countryid);

                db.Dispose();
            }
        }

        #endregion

    }
}